<template xmlns="http://www.w3.org/1999/html">
  <div class="modal modal-blur fade" id="modal-machine-plugin-ref" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <form id="machinePluginRefForm">
          <input type="hidden" name="machineIds" value=""/>
          <div class="modal-header">
            <h5 class="modal-title">更新机器插件</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label">更新管理框架</label>
              <select class="form-select" name="isUpdateManage" required>
                <option value="yes">更新</option>
                <option selected="selected" value="no">不更新</option>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">插件（可多选）</label>
              <select class="form-select" name="pluginIds" multiple required size="6">
                <option v-for="(item, index) in selectData" 
                        :key="index" 
                        :value="item.id">
                  {{ item.fullName }}
                </option>
              </select>
              <div class="form-text text-muted">
                按住 Ctrl(Windows) 或 Command(Mac) 键点击可选择多个选项
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label">清空当前机器所有插件</label>
              <select class="form-select" name="isClearPlugin" required>
                <option selected="selected" value="yes">清空</option>
                <option value="no">不清空</option>
              </select>
            </div>
          </div>
          <div class="modal-footer">
            <a href="#" class="btn btn-link link-secondary" data-bs-dismiss="modal">
              取消
            </a>
            <a href="#" class="btn btn-primary ms-auto" @click="submitMachineRef()">
              保存
            </a>
          </div>
        </form>
      </div>
    </div>

  </div>

  <ComponentModal
      :modalId="'modal-ref-machine'"
      :title="'信息'"
      :message="'操作成功'"
      :cancelText="'取消'"
      :confirmText="'确定'"
      ref="componentModalOutRef"
  />

  <Loading ref="loadingRef"/>

</template>

<script setup>
import {defineExpose, nextTick, ref, defineEmits} from "vue";
import {Modal} from "bootstrap";
import ComponentModal from "@/components/ComponentModal.vue";
import Loading from "@/components/Loading.vue";

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;

let machinePluginRefModal;

const componentModalOutRef = ref(null);

const selectData = ref([]);

const loadingRef = ref(null);

const emits = defineEmits(['updateSuccessEvent']);


nextTick(() => {
  // 添加机器模态框
  machinePluginRefModal = new Modal(document.getElementById('modal-machine-plugin-ref'));

  fetchSelect();
});

const fetchSelect = async () => {
  try {
    // 模拟API请求，替换为实际API调用
    const response = await fetch(apiBaseUrl + '/resident/plugin/searchPlugins'); // 替换为实际API
    const data = await response.json();
    if (data.success) {
      selectData.value = data.result.map(item => {
        let fullName = item.name + ' 【' + item.remark + '】';
        return {
          ...item,
          fullName
        };
      });
    }
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

const openMachinePluginRef = (machineIds) => {
  // 获取表单元素
  const machinePluginRefForm = document.getElementById('machinePluginRefForm');
  const formData = new FormData(machinePluginRefForm);
  machinePluginRefForm.reset(); // 重置表单，清空所有输入字段
  const machineIdsInput = machinePluginRefForm.elements.namedItem('machineIds');
  if (machineIdsInput) {
    // 设置 input 元素的值
    machineIdsInput.value = machineIds;
  }
  machinePluginRefModal.show(); // 打开
}

const submitMachineRef = async () => {
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000);

    try {
      // 获取表单元素
      const machinePluginRefForm = document.getElementById('machinePluginRefForm');
      const formData = new FormData(machinePluginRefForm);
      
      // 特殊处理多选的 select
      const data = {};
      const pluginSelect = machinePluginRefForm.querySelector('select[name="pluginIds"]');
      const selectedPlugins = Array.from(pluginSelect.selectedOptions).map(option => option.value);
      
      // 将其他表单数据添加到 data 对象
      formData.forEach((value, key) => {
        if (key !== 'pluginIds') {  // 跳过 pluginIds，因为我们已经特殊处理了
          data[key] = value;
        }
      });
      
      // 添加处理后的 pluginIds
      data.pluginIds = selectedPlugins.join(',');  // 或者直接使用数组: data.pluginIds = selectedPlugins;

      console.log(data);
      // 将数据对象转换为查询字符串
      const queryParams = new URLSearchParams(data).toString();
      // 构建完整的 URL，包含查询参数
      const url = `${apiBaseUrl}/resident/ref/update?${queryParams}`;
      loadingRef.value.openLoading();
      // 发送 POST 请求到后端接口
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });

      const apiResult = await response.json();

      clearTimeout(timeoutId);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      if (apiResult.success) {
        if (apiResult.errorMsg == null) {
          apiResult.errorMsg = '';
        }
        componentModalOutRef.value.openInfoModal('操作完成！' + apiResult.errorMsg);
        console.log('结束');
        setTimeout(() => {
          console.log('休眠1秒');
          machinePluginRefModal.hide();
          emits('updateSuccessEvent');
        }, 1000);
      } else {
        throw new Error(apiResult.errorMsg || '操作失败');
      }

    } catch (error) {
      if (error.name === 'AbortError') {
        componentModalOutRef.value.openWarnModal('请求超时，请检查网络连接！');
      } else {
        componentModalOutRef.value.openWarnModal('请求错误: ' + (error.message || '未知错误'));
      }
    }

  } catch (error) {
    componentModalOutRef.value.openWarnModal('系统错误，请稍后重试！');
    console.error('Submit error:', error);
  }
  loadingRef.value.closeLoading();

};

defineExpose({
  openMachinePluginRef
});
</script>

<style scoped>
.form-select[multiple] {
  padding: 8px;
  height: auto;
  min-height: 150px;
}

.form-select[multiple] option {
  padding: 8px;
  margin: 2px 0;
  border-radius: 4px;
}

.form-select[multiple] option:hover {
  background-color: #f8f9fa;
}

.form-select[multiple] option:checked {
  background-color: #0d6efd;
  color: white;
}
</style>